<template>
  <div class="ai-chat-wrapper">
    <!-- 悬浮球按钮 -->
    <div
      v-if="!showChat"
      class="ai-chat-bubble"
      :style="bubbleStyle"
      @mousedown="startDrag"
      @click="toggleChat"
    >
      <el-icon :size="28" class="chat-icon">
        <ChatDotRound />
      </el-icon>
      <div v-if="unreadCount > 0" class="unread-badge">{{ unreadCount }}</div>
    </div>

    <!-- 对话窗口 -->
    <transition name="slide-fade">
      <div v-if="showChat" class="ai-chat-window" :style="windowStyle">
        <!-- 标题栏 -->
        <div class="chat-header" @mousedown="startDrag">
          <div class="header-left">
            <el-icon :size="20"><Service /></el-icon>
            <span class="header-title">AI智能客服</span>
            <el-tag size="small" type="success" v-if="isConnected">在线</el-tag>
            <el-tag size="small" type="info" v-else>离线</el-tag>
          </div>
          <div class="header-right">
            <el-button text @click="minimizeChat">
              <el-icon><Minus /></el-icon>
            </el-button>
            <el-button text @click="closeChat">
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </div>

        <!-- 消息列表 -->
        <div class="chat-messages" ref="messagesContainer">
          <div
            v-for="(message, index) in messages"
            :key="index"
            :class="['message-item', message.role]"
          >
            <div class="message-avatar">
              <el-avatar :size="32" v-if="message.role === 'user'">
                <el-icon><User /></el-icon>
              </el-avatar>
              <el-avatar :size="32" v-else :style="{ background: '#409eff' }">
                <el-icon><ChatDotRound /></el-icon>
              </el-avatar>
            </div>
            <div class="message-content">
              <div class="message-bubble">
                <div class="message-text" v-html="formatMessage(message.content)"></div>
                <div class="message-time">{{ message.time }}</div>
              </div>
            </div>
          </div>

          <!-- 正在输入提示 -->
          <div v-if="isTyping" class="message-item assistant">
            <div class="message-avatar">
              <el-avatar :size="32" :style="{ background: '#409eff' }">
                <el-icon><ChatDotRound /></el-icon>
              </el-avatar>
            </div>
            <div class="message-content">
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入框 -->
        <div class="chat-input">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="2"
            placeholder="输入您的问题..."
            @keydown.enter.exact.prevent="sendMessage"
            @keydown.enter.shift.exact="inputMessage += '\n'"
          />
          <div class="input-actions">
            <el-button text size="small" @click="clearMessages">
              <el-icon><Delete /></el-icon>
              清空
            </el-button>
            <el-button
              type="primary"
              :disabled="!inputMessage.trim() || isSending"
              @click="sendMessage"
              :loading="isSending"
            >
              <el-icon v-if="!isSending"><Promotion /></el-icon>
              发送
            </el-button>
          </div>
        </div>

        <!-- 快捷问题 -->
        <div class="quick-questions" v-if="messages.length === 0">
          <div class="quick-title">常见问题：</div>
          <el-button
            v-for="(question, index) in quickQuestions"
            :key="index"
            size="small"
            text
            @click="sendQuickQuestion(question)"
          >
            {{ question }}
          </el-button>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick, onMounted, onUnmounted, getCurrentInstance } from 'vue';
import {
  ChatDotRound,
  Service,
  User,
  Close,
  Minus,
  Delete,
  Promotion
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const { proxy } = getCurrentInstance();

// 状态管理
const showChat = ref(false);
const messages = ref([]);
const inputMessage = ref('');
const isTyping = ref(false);
const isSending = ref(false);
const isConnected = ref(true);
const unreadCount = ref(0);
const messagesContainer = ref(null);

// 拖动相关
const isDragging = ref(false);
const dragStartX = ref(0);
const dragStartY = ref(0);
const position = reactive({
  x: window.innerWidth - 80,
  y: window.innerHeight - 80
});

// 样式计算
const bubbleStyle = computed(() => ({
  left: `${position.x}px`,
  top: `${position.y}px`,
  cursor: isDragging.value ? 'grabbing' : 'grab'
}));

const windowStyle = computed(() => ({
  right: '20px',
  bottom: '20px'
}));

// 快捷问题
const quickQuestions = ref([
  '如何查询库存？',
  '如何创建订单？',
  '发货流程是什么？',
  '如何查看实时大屏？'
]);

// 切换对话窗口
const toggleChat = () => {
  showChat.value = !showChat.value;
  if (showChat.value) {
    unreadCount.value = 0;
    nextTick(() => {
      scrollToBottom();
    });
  }
};

// 最小化
const minimizeChat = () => {
  showChat.value = false;
};

// 关闭
const closeChat = () => {
  showChat.value = false;
};

// 拖动开始
const startDrag = (e) => {
  if (showChat.value) return; // 窗口模式不允许拖动
  
  isDragging.value = true;
  dragStartX.value = e.clientX - position.x;
  dragStartY.value = e.clientY - position.y;
  
  document.addEventListener('mousemove', onDrag);
  document.addEventListener('mouseup', stopDrag);
};

// 拖动中
const onDrag = (e) => {
  if (!isDragging.value) return;
  
  let newX = e.clientX - dragStartX.value;
  let newY = e.clientY - dragStartY.value;
  
  // 限制在窗口范围内
  const maxX = window.innerWidth - 60;
  const maxY = window.innerHeight - 60;
  
  newX = Math.max(0, Math.min(newX, maxX));
  newY = Math.max(0, Math.min(newY, maxY));
  
  position.x = newX;
  position.y = newY;
};

// 拖动结束
const stopDrag = () => {
  isDragging.value = false;
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
};

// 发送消息
const sendMessage = async () => {
  const message = inputMessage.value.trim();
  if (!message || isSending.value) return;
  
  // 添加用户消息
  const userMessage = {
    role: 'user',
    content: message,
    time: getCurrentTime()
  };
  messages.value.push(userMessage);
  inputMessage.value = '';
  
  // 滚动到底部
  nextTick(() => {
    scrollToBottom();
  });
  
  // 显示正在输入
  isTyping.value = true;
  isSending.value = true;
  
  try {
    // 调用后端API（流式返回）
    const response = await fetch('/api/AICustomerService/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('Token')}`
      },
      body: JSON.stringify({
        message: message,
        sessionId: getSessionId()
      })
    });
    
    if (!response.ok) {
      throw new Error('网络请求失败');
    }
    
    // 创建AI回复消息
    const aiMessage = {
      role: 'assistant',
      content: '',
      time: getCurrentTime()
    };
    
    isTyping.value = false;
    messages.value.push(aiMessage);
    
    // 读取流式响应
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      
      const chunk = decoder.decode(value);
      const lines = chunk.split('\n');
      
      for (const line of lines) {
        if (line.startsWith('data:')) {
          const data = line.substring(5).trim();
          
          if (data === '[DONE]') {
            break;
          }
          
          try {
            const json = JSON.parse(data);
            if (json.content) {
              aiMessage.content += json.content;
              // 滚动到底部
              nextTick(() => {
                scrollToBottom();
              });
            }
            
            if (json.done) {
              break;
            }
            
            if (json.error) {
              ElMessage.error(json.message || 'AI服务错误');
              break;
            }
          } catch (e) {
            console.warn('解析响应数据失败:', e);
          }
        }
      }
    }
    
    // 如果窗口未打开，增加未读数
    if (!showChat.value) {
      unreadCount.value++;
    }
    
  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error('消息发送失败，请稍后重试');
    isTyping.value = false;
    
    // 添加错误提示消息
    messages.value.push({
      role: 'assistant',
      content: '抱歉，我暂时无法回答您的问题。请稍后再试。',
      time: getCurrentTime()
    });
  } finally {
    isSending.value = false;
    isTyping.value = false;
  }
};

// 发送快捷问题
const sendQuickQuestion = (question) => {
  inputMessage.value = question;
  sendMessage();
};

// 清空消息
const clearMessages = () => {
  messages.value = [];
  ElMessage.success('已清空对话记录');
};

// 格式化消息（支持简单的Markdown）
const formatMessage = (text) => {
  return text
    .replace(/\n/g, '<br>')
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/`(.*?)`/g, '<code>$1</code>');
};

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date();
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  return `${hours}:${minutes}`;
};

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

// 获取会话ID
const getSessionId = () => {
  let sessionId = sessionStorage.getItem('ai_session_id');
  if (!sessionId) {
    sessionId = 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    sessionStorage.setItem('ai_session_id', sessionId);
  }
  return sessionId;
};

// 监听窗口大小变化
const handleResize = () => {
  const maxX = window.innerWidth - 60;
  const maxY = window.innerHeight - 60;
  
  position.x = Math.min(position.x, maxX);
  position.y = Math.min(position.y, maxY);
};

// 组件挂载
onMounted(() => {
  window.addEventListener('resize', handleResize);
  
  // 加载历史消息（可选）
  const savedMessages = sessionStorage.getItem('ai_chat_messages');
  if (savedMessages) {
    try {
      messages.value = JSON.parse(savedMessages);
    } catch (e) {
      console.warn('加载历史消息失败');
    }
  }
});

// 组件卸载
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  
  // 保存消息历史（可选）
  sessionStorage.setItem('ai_chat_messages', JSON.stringify(messages.value));
});

// 监听消息变化，自动保存
watch(() => messages.value.length, () => {
  sessionStorage.setItem('ai_chat_messages', JSON.stringify(messages.value));
});
</script>

<style scoped lang="less">
.ai-chat-wrapper {
  position: fixed;
  z-index: 9999;
}

// 悬浮球
.ai-chat-bubble {
  position: fixed;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    transform: scale(1.1);
    box-shadow: 0 6px 30px rgba(102, 126, 234, 0.6);
  }
  
  .chat-icon {
    color: #fff;
  }
  
  .unread-badge {
    position: absolute;
    top: -5px;
    right: -5px;
    background: #f56c6c;
    color: #fff;
    font-size: 12px;
    font-weight: bold;
    min-width: 20px;
    height: 20px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 6px;
    box-shadow: 0 2px 8px rgba(245, 108, 108, 0.4);
  }
}

// 对话窗口
.ai-chat-window {
  position: fixed;
  width: 380px;
  height: 600px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 40px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  
  // 标题栏
  .chat-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    padding: 15px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: move;
    user-select: none;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 10px;
      
      .header-title {
        font-size: 16px;
        font-weight: 500;
      }
    }
    
    .header-right {
      display: flex;
      gap: 5px;
      
      .el-button {
        color: #fff;
        
        &:hover {
          background: rgba(255, 255, 255, 0.2);
        }
      }
    }
  }
  
  // 消息列表
  .chat-messages {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    background: #f5f7fa;
    
    &::-webkit-scrollbar {
      width: 6px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #dcdfe6;
      border-radius: 3px;
    }
    
    .message-item {
      display: flex;
      gap: 12px;
      margin-bottom: 20px;
      animation: slideIn 0.3s ease;
      
      &.user {
        flex-direction: row-reverse;
        
        .message-bubble {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: #fff;
        }
      }
      
      &.assistant {
        .message-bubble {
          background: #fff;
          color: #303133;
        }
      }
      
      .message-avatar {
        flex-shrink: 0;
      }
      
      .message-content {
        max-width: 70%;
        
        .message-bubble {
          padding: 12px 16px;
          border-radius: 12px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
          
          .message-text {
            word-break: break-word;
            line-height: 1.6;
            
            :deep(code) {
              background: rgba(0, 0, 0, 0.1);
              padding: 2px 6px;
              border-radius: 4px;
              font-family: 'Courier New', monospace;
            }
          }
          
          .message-time {
            margin-top: 8px;
            font-size: 12px;
            opacity: 0.7;
          }
        }
      }
    }
    
    // 正在输入动画
    .typing-indicator {
      display: flex;
      gap: 4px;
      padding: 12px 16px;
      background: #fff;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      
      span {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: #909399;
        animation: typing 1.4s infinite;
        
        &:nth-child(2) {
          animation-delay: 0.2s;
        }
        
        &:nth-child(3) {
          animation-delay: 0.4s;
        }
      }
    }
  }
  
  // 输入框
  .chat-input {
    padding: 15px 20px;
    background: #fff;
    border-top: 1px solid #e4e7ed;
    
    .input-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 10px;
    }
  }
  
  // 快捷问题
  .quick-questions {
    padding: 15px 20px;
    background: #f5f7fa;
    border-top: 1px solid #e4e7ed;
    
    .quick-title {
      font-size: 13px;
      color: #909399;
      margin-bottom: 10px;
    }
    
    .el-button {
      margin: 5px 5px 0 0;
    }
  }
}

// 滑入动画
.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.3s ease;
}

.slide-fade-enter-from {
  transform: translateY(20px);
  opacity: 0;
}

.slide-fade-leave-to {
  transform: translateY(20px);
  opacity: 0;
}

// 消息滑入动画
@keyframes slideIn {
  from {
    transform: translateY(10px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

// 打字动画
@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}
</style>

